package com.lichuandi.fx;


import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.BorderPane;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import java.io.File;
import java.nio.file.Files;

public class JavaFXNotepad extends Application {
    private TextArea textArea;
    private File currentFile;

    @Override
    public void start(Stage primaryStage) {
        // 文本编辑区
        textArea = new TextArea();
        BorderPane root = new BorderPane(textArea);

        // 菜单栏
        MenuBar menuBar = new MenuBar();
        Menu fileMenu = new Menu("文件");

        MenuItem openItem = new MenuItem("打开");
        openItem.setOnAction(e -> openFile(primaryStage));

        MenuItem saveItem = new MenuItem("保存");
        saveItem.setOnAction(e -> saveFile(primaryStage));

        fileMenu.getItems().addAll(openItem, saveItem);
        menuBar.getMenus().add(fileMenu);
        root.setTop(menuBar);

        // 窗口设置
        Scene scene = new Scene(root, 800, 600);
        primaryStage.setTitle("JavaFX 记事本");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    private void openFile(Stage stage) {
        FileChooser fileChooser = new FileChooser();
        File file = fileChooser.showOpenDialog(stage);
        if (file != null) {
            try {
                textArea.setText(Files.readString(file.toPath()));
                currentFile = file;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void saveFile(Stage stage) {
        if (currentFile == null) {
            FileChooser fileChooser = new FileChooser();
            currentFile = fileChooser.showSaveDialog(stage);
        }
        if (currentFile != null) {
            try {
                Files.writeString(currentFile.toPath(), textArea.getText());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        launch(args);
    }
}
